%Minimizing the Variance of Returns
%This m file calculates the weights for the simulated portfolios
% The results of these simulations are reported in Appendix Table 8


%The data should be in the following format:
%columns 1-2: blank
%columns 3-8: global fund returns
%columns 9-21: specialized fund returns
%column 22: benchmark index return
%columns 23-36: blank
%column 37: simid ("s" in the code)
%column 38: t (time period)

data1 = textread('data.out', '', 'delimiter', ',','emptyvalue', 1000);

sim=data1(:,37);
[r,c]=size(sim);
dataF = [];

% Loop over the number of simulated portfolios (vary with the data
% frequency and type of simulation):
for s=1:165

%Defining the initial period for the simulations
%Daily data: 50 business days
%Weekly data: 10 weeks
%Monthly data: 5 months
    t0=50;                  
    
    t = find(sim == s);
    b = min(t);
    e = max(t);
    
    glb= data1(b:e,22);
    [rg,cg]=size(glb);
    
    specialized = data1(b:e,9:21);
    reg2=[];
    i3=1;
    for i3=1:13
        rmc = max(specialized(:,14-i3));
        if rmc == 1000
        reg2= data1(b:e,9:21-i3);
        end
    end
    
    test=[];
    test2=isequal(test,reg2);
    if test2 == 1,
        reg2=specialized;
    end

    specialized = reg2;
    clear reg2 i3 rmc 

   ind = data1(b:e,22);
   
   ret = [glb specialized ind];
   [r,c]=size(ret);

X=[];
x=[];
new=[];
original2=[];
xz=[];
A=[];
bb=[];
Aeq=[];
beq=[];
lb=[];
ub=[];
sigma=[];
retx=[];
index=[];
original=[];
index1=[];

nt = c; 
n=nt-1;
T = r;  
gf=cg;  

xz(1:n,1)=0;             
xz(1,1)=0;
X=zeros(1,n+1);

i=1;
for t=t0:T
    retx=ret(1:t,1:nt);

index1=retx(:,nt);
retx(:,nt)=[]  ;
one=ones(n,1);                      
index=index1*one.';                 
mainglb=retx(:,1)  ;         

sigma = cov(retx);  
M=mean(retx);      
A=-M;              
bb=-mean(mainglb);
Aeq=ones(n,1)';    
beq=1;             
f=zeros(n,1);      
ub=ones(n,1);      
lb=zeros(n,1);     

[x, favl, exitflag, output, lambda] = minvar(xz,A,bb,Aeq,beq,lb,ub,sigma,retx,index,mainglb,index1);
new = [x' i];
X = [X; new];
i=i+1

end

xnew = zeros(48,c);
xnew= [xnew; X];
xnew2=xnew;
xnew2(:,c)=[];
ret2=ret;
ret2(:,nt)=[];
ret2(1,:)=[];
last=ret2(1,:);
last(1,:)=0;
ret2=[ret2; last];
retnew=ret2*xnew2';
retnew2=diag(retnew,0);
retnew2=[0; retnew2];
retnew2(r+1,:)=[];
rr=38-(22+c)
z=ones(e-b+1,rr)*1000;

dataF = [dataF; data1(b:e,37:38) data1(b:e,3:8) data1(b:e,9:21) xnew2 z  data1(b:e,1:2) retnew2 ind];

end

dlmwrite('data1_BM_VAR.out',dataF, ',');

